package com.example.contact_recover;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.contact_recover.models.ContactsInfo;
import com.example.contact_recover.models.Message;
import com.example.contact_recover.models.User;
import com.example.contact_recover.util.NetUtil;
import com.example.contact_recover.vv.ContactAdapter;

import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import droidninja.filepicker.FilePickerBuilder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity {

    private static final int REQ_PIC = 234;
    private String TAG = "pullContact";

    private static final int REQ_CONTACT = 233;
    private String phone;
    private String passwd;
    private RecyclerView rv_contacts;
    private ContactAdapter contactAdapter;
    private List<Message> smsList = new ArrayList<>();
    private User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        rv_contacts = findViewById(R.id.rv_contacts);
        rv_contacts.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));


    }

    @Override
    protected void onStart() {
        super.onStart();

        SharedPreferences lastLogin = getSharedPreferences("last_login", MODE_PRIVATE);

        boolean ok = lastLogin.contains("phone");

        if (!ok) {
            // todo goto login
            finish();
            startActivity(new Intent(this, LoginActivity.class));
        }

        phone = lastLogin.getString(getResources().getString(R.string.title_phone), "");
        passwd = lastLogin.getString(getResources().getString(R.string.title_passwd), "");
        long id = lastLogin.getLong("id", -1);


        user = LitePal.find(User.class, id, true);

        if (user == null) {
            Toast.makeText(this, "null ", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 设置 数据源
        contactAdapter = new ContactAdapter(user.getContactsList());
        rv_contacts.setAdapter(contactAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (!EasyPermissions.hasPermissions(this, Manifest.permission.READ_CONTACTS,Manifest.permission.READ_SMS, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_CONTACTS, Manifest.permission.CALL_PHONE, Manifest.permission.SEND_SMS)) {

            // todo request permission
            EasyPermissions.requestPermissions(MainActivity.this, "need your contacts' permission", REQ_CONTACT, Manifest.permission.READ_SMS,Manifest.permission.READ_CONTACTS, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS, Manifest.permission.CALL_PHONE, Manifest.permission.SEND_SMS);
            return false;
        }

        switch (item.getItemId()) {


            case R.id.menu_recover: {


                Log.i(TAG, " phone = " + phone + " passwd = " + passwd);
                // 拉取用户数据
                NetUtil.pull2Server(
                        NetUtil.SERVER_PULL + "/user/pull?phone=" + phone + "&passwd=" + passwd,
                        new pullContacts());


            }
            break;

            case R.id.menu_save: {

                List<ContactsInfo> contactsInfos = ContactsInfo.readContacts(MainActivity.this);

                for (ContactsInfo info : contactsInfos) {


                    System.out.println("info " + info + " , json " + JSONObject.toJSONString(info));
                }

                User user = new User();

                user.setPasswd(passwd);
                user.setPhone(phone);
                user.setContactsList(contactsInfos);

                // 把联系人推送到服务器
                NetUtil.push2Server(NetUtil.SERVER_PULL + "/user/push", user, new pushContacts());

                System.out.println("lllll ==== " + JSON.toJSON(contactsInfos));

            }
            break;

            case R.id.menu_add: {
                testAddContacts();
            }
            break;

            case R.id.menu_out: {

                SharedPreferences lastLogin = getSharedPreferences("last_login", MODE_PRIVATE);
                SharedPreferences.Editor editor = lastLogin.edit();

                editor.remove("phone");
                editor.remove("passwd");
                editor.remove("id");
                editor.apply();

                onStart();
            }
            break;

            case R.id.menu_web: {
                System.out.println("click menu web ..... ");
                startActivity(new Intent(this, WebVActivity.class));
            }
            break;

            // 跳转到打电话的页面
            case R.id.menu_call_button: {
                //startActivity(new Intent(Intent.ACTION_CALL_BUTTON));

                // 带参数的跳转...
                startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "132")));
            }
            break;

            case R.id.menu_select_pic: {

                // 使用第三方的 文件选择器, 包括 拍照
                FilePickerBuilder.getInstance().
                        setActivityTitle("pic picture").
                        setMaxCount(4).
                        enableCameraSupport(true).
                        pickPhoto(MainActivity.this, REQ_PIC);

            }
            break;
            // 备份短信
            case R.id.menu_cp_sms: {

                cpSms();

                if (smsList.size() != 0){
                    // 备份短信

                    User user = new User();
                    user.setPhone(phone);
                    user.setPasswd(passwd);
                    NetUtil.push2Server(NetUtil.SERVER_PULL+"/user/cpsms",user ,smsList,new cpSmsBack());
                }
            }
            break;
            // 恢复短信
            case R.id.menu_recover_sms: {

            }
            break;
            default: {

            }
            break;
        }
        return true;
    }


    class pushContacts implements Callback {

        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            byte[] bytes = response.body().bytes();

            String text = new String(bytes, 0, bytes.length);
            System.out.println("text = " + text);
        }
    }

    class pullContacts implements Callback {


        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            // user
            byte[] bytes = response.body().bytes();

            String text = new String(bytes, 0, bytes.length);
            // Log.i(TAG,"text = "+ text );

            User user = JSON.parseObject(text, User.class);
            user.saveOrUpdate();
            for (ContactsInfo info : user.getContactsList()) {
                info.setUser(user);
                boolean b = info.save();

                Log.i("sa?", "xx " + info);
            }

            Log.i(TAG, "user " + user);
            System.out.println("user " + user);

            runOnUiThread(() -> {
                contactAdapter = new ContactAdapter(user.getContactsList());
                rv_contacts.setAdapter(contactAdapter);
                // notify data set changed safe ....
                contactAdapter.notifyDataSetChanged();
            });
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data == null) {
            return;
        }

        switch (requestCode) {
            case REQ_PIC: {

                // 这里不做获取图片的处理......
            }
            break;
        }
    }

    public void testAddContacts() {
        //插入raw_contacts表，并获取_id属性
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        ContentResolver resolver = getApplicationContext().getContentResolver();
        ContentValues values = new ContentValues();
        long contact_id = ContentUris.parseId(resolver.insert(uri, values));
        //插入data表
        uri = Uri.parse("content://com.android.contacts/data");
        //add Name
        values.put("raw_contact_id", contact_id);
        values.put(ContactsContract.Contacts.Data.MIMETYPE, "vnd.android.cursor.item/name");
        values.put("data2", "zdong");
        values.put("data1", "xzdong");
        resolver.insert(uri, values);
        values.clear();
        //add Phone
        values.put("raw_contact_id", contact_id);
        values.put(ContactsContract.Contacts.Data.MIMETYPE, "vnd.android.cursor.item/phone_v2");
        values.put("data2", "2");   //手机
        values.put("data1", "87654321");
        resolver.insert(uri, values);
        values.clear();
        //add email
        values.put("raw_contact_id", contact_id);
        values.put(ContactsContract.Contacts.Data.MIMETYPE, "vnd.android.cursor.item/email_v2");
        values.put("data2", "2");   //单位
        values.put("data1", "xzdong@xzdong.com");
        resolver.insert(uri, values);
    }


    // 添加联系人...
    private void addContacts(String name, String num) {
        ContentValues values = new ContentValues();
        Uri rawContactUri = getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, values);
        long rawContactId = ContentUris.parseId(rawContactUri);

        values.clear();
        values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
        values.put(ContactsContract.Contacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
        values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, name);
//    	values.put(StructuredName.FAMILY_NAME, "Mike");


        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);

        values.clear();
        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, num);
        values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME);
//    	values.put(Email.DATA, "ligang.02@163.com");
//    	values.put(Email.TYPE, Email.TYPE_WORK);
        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
    }


    public void cpSms() {
        smsList.clear();
        //访问内容提供者获取短信
        ContentResolver cr = getContentResolver();
        //            短信内容提供者的主机名
        Cursor cursor = cr.query(Uri.parse("content://sms"), new String[]{"address", "date", "body", "type"},
                null, null, null);
        if (cursor == null){
            return ;
        }
        while (cursor.moveToNext()) {
            String address = cursor.getString(0);
            long date = cursor.getLong(1);
            String body = cursor.getString(2);
            String type = cursor.getString(3);
            Message sms = new Message(body, type, address, date);
            smsList.add(sms);
            Log.e("TAG", sms.toString());
        }
    }

    class cpSmsBack implements Callback{

        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

        }
    }
}
